import 'package:get/get.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:smart_devices/model/api_response.dart';
import 'package:smart_devices/model/paging_data.dart';

mixin PageMixin<T> on GetLifeCycleBase {
  RxString search = RxString('');

  RefreshController refreshController = RefreshController();

  /// 总条数
  RxInt total = RxInt(0);

  /// 总页数
  RxInt pages = RxInt(0);

  /// 每页大小
  RxInt size = RxInt(10);

  /// 当前页
  RxInt current = RxInt(1);

  /// 数据
  RxList<T> pageList = RxList([]);

  T fromJsonT(Object? json);

  @override
  void onClose() {
    super.onClose();
    refreshController.dispose();
  }

  /// 加载数据
  Future<ApiResponse<PagingDataModel<T>>> loadMoreData();

  Future<void> onRefresh() async {
    /// 发起请求
    return await Future.delayed(const Duration(milliseconds: 2000), () async {
      // ApiResponse<dynamic> response = await loadMoreData();
      refreshController.refreshCompleted(resetFooterState: true);
    });
  }

  Future<void> onLoading() async {
    /// 发起异步请求
    return await Future.delayed(const Duration(milliseconds: 200), () async {
      if (pageList.length > total.value) {
        return refreshController.loadNoData();
      }
      ApiResponse<dynamic> response = await loadMoreData();
      if (response.data != null) {
        Map<String, dynamic> json = response.data;
        PagingDataModel<T> paging = PagingDataModel.fromJson(json, fromJsonT);
        pageList.addAll(paging.data!);
        total.value = paging.total!;
      }
      refreshController.loadComplete();
    });
  }
}
